package io;

import java.io.*;
import java.net.*;

/**
 * Created by fanzhenyu02 on 2020/7/4.
 */
public class SocketServer {

    public static int port = 4343; //端口号

    public static void main(String[] args) {
        // Socket 服务器端（简单的发送信息）
        Thread serverThread = new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("服务器启动");

                try {
                    ServerSocket serverSocket = new ServerSocket(port);
                    while (true) {
                        // 等待连接
                        Socket socket = serverSocket.accept();
                        Thread serverHandlerThread = new Thread(new Runnable() {
                            @Override
                            public void run() {
                                System.out.println("接收到客户端请求...");
                                try (PrintWriter printWriter = new PrintWriter(socket.getOutputStream())) {
                                    printWriter.println("hello world！");
                                    printWriter.flush();
                                } catch (IOException e) {
                                    e.printStackTrace();
                                }
                            }
                        });
                        serverHandlerThread.start();
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        serverThread.start();
    }
}
